package twt.practice.votingsystem.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import twt.practice.votingsystem.dao.VoteMapper;
import twt.practice.votingsystem.service.VoteService;
import twt.practice.votingsystem.utils.APIResponse;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class VoteServiceImpl implements VoteService {

    @Autowired
    VoteMapper voteMapper;

    private static ReentrantLock lock = new ReentrantLock();

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse getVote(){
        lock.lock();
        try {
            return APIResponse.success(voteMapper.getVote());
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "查询失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse getChoice(Integer title_id){
        lock.lock();
        try {
            return APIResponse.success(voteMapper.getChoice(title_id));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "查询失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse Voting(Integer title_id, Integer choice_id){
        lock.lock();
        try {
            return APIResponse.success(voteMapper.Voting(title_id, choice_id));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "投票失败");
        }finally {
            lock.unlock();
        }
    }
}
